﻿using STTech.BytesIO.Core;
using STTech.BytesIO.Serial;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPF.BytesIO.Serial.Models;
using WPF.BytesIO.Serial.ModelViews;

namespace WPF.BytesIO.Serial
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainViewModel ViewModel { get { return App.MainViewModel; } }

        private SerialClient Client;
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = ViewModel;

            this.Loaded += delegate
            {
                Client = new SerialClient();

                Client.OnDataReceived += Client_OnDataReceived;

                Client.OnConnectedSuccessfully += Client_OnConnectedSuccessfully;

                Client.OnDisconnected += Client_OnDisconnected;

            };
        }

        private void Client_OnDisconnected(object sender, DisconnectedEventArgs e)
        {
            if (Client.IsConnected)
            {
                ViewModel.SerialStatus.Update($"已连接", MyBrushes.Green);
            }
            else
            {
                ViewModel.SerialStatus.Update($"未连接", MyBrushes.Red);
            }
        }

        private void Client_OnConnectedSuccessfully(object sender, ConnectedSuccessfullyEventArgs e)
        {
            ViewModel.SerialStatus.Update($"已连接", MyBrushes.Green);
        }

        private void Client_OnDataReceived(object sender, DataReceivedEventArgs e)
        {
            Print($"收到数据：{e.Data.EncodeToString("UTF-8")}", MyBrushes.Green);
        }

        #region 打印log
        private Block Print(string data, MyBrushes statusBrush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetBlock(data, statusBrush);

                this.rtxtLogName.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = Print(data, statusBrush);
                });
            }

            return block;
        }
        private Block GetBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }
        private void tbnCleanRickTextBoxContent_OnClick(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
            {
                rtxtLogName.Document.Blocks.Clear();
            });
        }
        #endregion

        private void btnConnectSerial_OnClick(object sender, RoutedEventArgs e)
        {
            if (Client != null)
            {

                Client.PortName = ViewModel.TestInfo.PortName;

                Client.BaudRate = ViewModel.TestInfo.RaudRate;

                Client.DataBits = ViewModel.TestInfo.DataBits;

                Client.Parity = System.IO.Ports.Parity.None;

                Client.StopBits = System.IO.Ports.StopBits.One;

                Client.NewLine = "\r\n";
                //Client.SendBufferSize = 4096;
                //Client.DtrEnable = true;

                //Client.RtsEnable = true;
                Client.Connect();
            }
        }
        private void btnDisConnectSerial_OnClick(object sender, RoutedEventArgs e)
        {
            if(Client != null)
            {
                Client.Disconnect();
            }
        }

        private void btnGetInfo_OnClick(object sender, RoutedEventArgs e)
        {
            if (Client != null && Client.IsConnected)
            {
                //Encoding encoding = Encoding.Default;

                Client.SendAsync(Encoding.Default.GetBytes("INFO"));
         
            
            }
        }

        private void btnSend_OnClick(object sender, RoutedEventArgs e)
        {
            if (Client != null && Client.IsConnected)
                Client.SendAsync(Encoding.Default.GetBytes(ViewModel.TestInfo.ClientSendMsg));
        }
    }
}
